package com;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

public class Processor extends Thread{
	
	private Socket socket;
	private InputStream in;
	private PrintStream out;
	final static String WEB_ROOT = "D:\\opensource\\webserver\\htdocs";
	
	public Processor(Socket socket){
		this.socket = socket;
		try {
			this.in = socket.getInputStream();
			this.out = new PrintStream(socket.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void run(){
		String fileName = parse(in);
		sendFile(fileName);
	}
	
	/**
	 * 获取资源名称
	 * @return
	 */
	public String parse(InputStream inputStream){
		BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
		String fileName="";
		try {
			String httpMessage = br.readLine();
			String[] content = httpMessage.split(" ");
			
			if(content.length!=3){
				sendErrorMessage(400,"Client Query Error!");
				return null;
			}
			
			System.out.println("code:"+content[0]+",filename:"+content[1]+",http version:"+content[2]);
			fileName = content[1];
		} catch (IOException e) {
			e.printStackTrace();
		}
		return fileName;
	}
	/**
	 * 返回错误信息
	 * @param errorCode
	 * @param errorMessage
	 */
	public void sendErrorMessage(int errorCode,String errorMessage){
		out.println("http/1.1 "+errorCode+" "+errorMessage);
		out.println("content-type:text/html");
		out.println();
		out.println("<html>");
		out.println("<title>Error Message");
		out.println("</title>");
		out.println("<body>");
		out.println("<h1>ErrorCode:"+errorCode+",ErrorMessage:"+errorMessage+"</h1>");
		out.println("</body>");
		out.println("</html>");
		out.flush();
		out.close();
	}
	public void sendFile(String fileName){
		File file = new File(Processor.WEB_ROOT+fileName);
		if(!file.exists()){
			sendErrorMessage(404,"File Not Found!");
			return;
		}else{
			try {
				InputStream inputStream = new FileInputStream(file);
				byte[] content = new byte[(int)file.length()];
				inputStream.read(content);
				out.println("http/1.1 200 queryfile");
				out.println("content-length:"+content.length);
				out.println();
				out.write(content);
				out.flush();
				out.close();
				inputStream.close();
				
				
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
